<template>
  <el-col>
    <div class="equipment-detail-button">
      <!-- <el-button >全部展开</el-button> -->
      <el-button @click="() => getCheckedKeys()">保存</el-button>
      <el-button @click="expandAll">全部展开</el-button>
    </div>
    <el-tree
      :node-contextmenu="clickRight"
      :data="orgData"
      :show-checkbox="showCheckbox"
      node-key="organId"
      :default-expand-all="true"
      :default-checked-keys="checkbox"
      :props="defaultProps"
      ref="tree"
      :check-strictly="true"
      @check="checkedNodes"
    >
      <span
        class="custom-tree-node"
        slot-scope="{ node, data }"
        @mouseenter="mouseenter(data)"
        @mouseleave="mouseleave(data)"
      >
        <span :class="highlightText(node) ? 'tree-blue' : 'tree-common'">{{
          node.label
        }}</span>
        <span class="custom-tree-node-btn" v-if="showOperateBtn">
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            @click="() => upRemove(data, node)"
            >上移</el-button
          >
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            @click="() => downRemove(data, node)"
            >下移</el-button
          >
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            @click="() => add(data)"
            >新增</el-button
          >
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            @click="() => rename(data)"
            >更名</el-button
          >
          <el-button
            v-show="data.show"
            type="text"
            size="mini"
            class="fontRed"
            v-if="data.isSys !== 1"
            @click="() => del(data)"
            >删除</el-button
          >
        </span>
      </span>
    </el-tree>
    <DownloadIdentify
      @cancel="cancel"
      @update="() => dialogSubmit(1)"
      :visible.sync="dialogVisible"
      title="部门管理"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="部门名" prop="organName">
          <el-input v-model="ruleForm.organName" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="级别" prop="floor">
          <el-select
            v-model="ruleForm.floor"
            placeholder="级别"
            :disabled="isEdit"
          >
            <el-option label="本级" value="1"></el-option>
            <el-option label="下级" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </DownloadIdentify>
    <DownloadIdentify
      @cancel="cancel"
      @update="() => dialogSubmit(2)"
      :visible.sync="updateNamedialogVisible"
      title="部门管理"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="部门名" prop="organName">
          <el-input v-model="ruleForm.organName" maxlength="10"></el-input>
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </el-col>
</template>

<script>
import DownloadIdentify from "@/components/FormDialog";
import { mapState, mapMutations } from "vuex";
export default {
  components: { DownloadIdentify },
  watch: {
    checkbox: function (newValue) {
      this.$refs.tree.setCheckedKeys(newValue);
      console.log("checkbox", newValue);
    },
  },
  props: [
    "actionUrl",
    "showCheckbox",
    "showOperateBtn",
    "tableData",
    "checkbox",
    "getCheckedKeys",
  ],
  data() {
    return {
      dialogVisible: false,
      updateNamedialogVisible: false,
      orgData: [],
      // checkedbox:[],
      currentNode: "",
      isEdit: false,
      ruleForm: {
        id: "",
        organName: "",
        floor: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        region: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
        is_show: true,
      },
    };
  },
  mounted() {
    setTimeout(() => {
      this.orgData = this.$store.state.app.allCode.department;
    }, 500);
    //this.orgData.push([...this.$store.state.app.allCode.department])
  },

  computed: {
    ...mapState(["app"]),
  },
  methods: {
    expandAll() {
      for (var i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
        this.$refs.tree.store._getAllNodes()[i].expanded = true;
      }
    },
    //对适用的部门高亮
    highlightText(node) {
      if (this.tableData && this.tableData.row.organIds) {
        //高亮
        if (this.tableData.row.organIds.indexOf(node.data.organId) != -1) {
          return true;
        }
      } else {
        return false;
      }
    },
    clickRight(event, data, node, self) {
      console.log(data);
    },
    mouseenter(data) {
      this.$set(data, "show", true);
    },
    mouseleave(data) {
      this.$set(data, "show", false);
    },
    checkedNodes(checkedNodes, checkedKeys) {
      //点击复选框则需要向vuex同步一次  需要动态用ref来区分不同业务得树
      console.log(checkedKeys, "-*-");
      const data = checkedKeys.checkedKeys;
      this.$store.dispatch(`${this.actionUrl}`, data);
    },
    dialogSubmit(isAdd) {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);

          this.ruleForm.id = this.currentNode.id;
          if (this.ruleForm.floor != 2) {
            this.ruleForm.parentId = this.currentNode.parentId;
            //本级
            this.ruleForm.level = this.currentNode.level;
          } else {
            this.ruleForm.parentId = this.currentNode.id;
            //下级
            this.ruleForm.level = this.currentNode.level + 1;
          }
          const data = JSON.parse(JSON.stringify(this.ruleForm));
          data.isAdd = isAdd;
          this.$store.dispatch("system_department/saveDepartmentInfo", data);
          this.$store.dispatch("app/getCodeList", ["department"]); //code转码

          setTimeout(() => {
            this.$set(
              this,
              "orgData",
              this.$store.state.app.allCode.department
            );
          }, 500);
          //this.$router.go(0);
          //this.orgData = this.$store.state.app.allCode.department;
          if (isAdd == 1) {
            //1为新增2为更名
            this.dialogVisible = false;
          } else {
            this.updateNamedialogVisible = false;
          }
          // this.$set(this, "orgData", this.$store.state.app.allCode.department);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancel() {
      this.dialogVisible = false;
      this.updateNamedialogVisible = false;
    },
    //五个操作方法 上移下移删除添加更名
    //新增
    add(e) {
      console.log(e, "+++add++++");
      this.ruleForm = {
        id: "",
        organName: "",
        floor: "",
      };
      if (e.level >= 4) {
        this.ruleForm.floor = "1";
        this.isEdit = true;
      } else {
        this.ruleForm.floor = "";
        this.isEdit = false;
      }
      this.currentNode = e;
      this.dialogVisible = true;
    },
    //更名
    rename(e) {
      this.currentNode = e;
      this.ruleForm.organName = e.label;
      this.updateNamedialogVisible = true;
    },
    //删除
    del(row) {
      console.log(row);
      this.$confirm(
        `确认删除该部门？请先确保：

1.该部门无下级部门

2.该部门内无账号

3.该部门内无设备

4.该部门内无备件`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$store
            .dispatch("system_department/delOrg", row.id)
            .then((response) => {
              // this.$message({
              //   type: "success",
              //   message: "删除成功!"
              // });
              // this.dialogVisible=true
              this.$store.dispatch("app/getCodeList", ["department"]); //code转码
              setTimeout(() => {
                this.$set(
                  this,
                  "orgData",
                  this.$store.state.app.allCode.department
                );
              }, 500);
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "删除失败",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //上移
    upRemove(e, n) {
      console.log(e, "+++++e++++");
      console.log(n.previousSibling.data, "----node----");

      let currNode = JSON.parse(JSON.stringify(e));
      let previous = JSON.parse(JSON.stringify(n.previousSibling.data));
      if (previous) {
        currNode.organSort = n.previousSibling.data.organSort;
        previous.organSort = e.organSort;

        this.$store.dispatch(
          "system_department/sortDepartmentInfo",
          [previous, currNode]
          //  [
          //   n.previousSibling.data,
          //   e
          // ]
        );
      } else {
        this.$message("第一条数据无法上移");
      }

      //this.dialogVisible=true
    },
    //下移
    downRemove(e, n) {
      this.currentNode = e;
      let currNode = JSON.parse(JSON.stringify(e));
      let nextSibling = JSON.parse(JSON.stringify(n.nextSibling.data));

      this.$store.dispatch("system_department/sortDepartmentInfo", [
        nextSibling,
        currNode,
      ]);
      if (nextSibling) {
        currNode.organSort = n.nextSibling.data.organSort;
        nextSibling.organSort = e.organSort;

        this.$store.dispatch(
          "system_department/sortDepartmentInfo",
          [nextSibling, currNode]
          //  [
          //   n.previousSibling.data,
          //   e
          // ]
        );
      } else {
        this.$message("最后一条数据无法下移");
      }
    },
    renderContent(h, { node, data, store }) {
      if (node.highlight) {
        return (
          <span class="custom-tree-node">
            <span style="color:blue">{node.label}</span>
          </span>
        );
      } else {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
          </span>
        );
      }
    },
  },
};
</script>
<style lang="scss">
.el-tree {
  background: #f6f8fa;
}
.custom-tree-node-btn {
  margin-left: 15px;
  font-size: 12px;
}
.tree-blue {
  color: blue;
}
.tree-common {
  color: black;
}
</style>
